package YourSpace::Controller::Blog;
# $WCREV WVDATE$
use strict;
use warnings;
use base 'Catalyst::Controller';
use POSIX;
=head1 NAME

YourSpace::Controller::Blog - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index 

=cut

sub index : Private {
    my ( $self, $c ) = @_;
    $c->stash->{posts}    = get_blogs(); 
    $c->stash->{template} = 'blog/index.tt2';
}

sub get_blogs {
    my ($self, $c, $page) = @_;
    my $blogs;
    foreach my $blog (
        $c->model('YourSpaceDB::Blog')->search(
            {
                blog_is_hidden => 0,
                blog_is_reply  => 0,
                blog_is_draft  => 0,
            },  
            {  
                rows           => 5,
                page           => $page,
                order_by       => 'blog_date DESC'
            }  
        )->all) {
        push @$blogs, get_replies($c, $blog, $page);
    }
    $blogs;
}

sub get_replies {
    my ($c, $blog, $page) = @_;

    my $replies;
    my $ret;
   
    my $replies = $c->model('YourSpaceDB::Blog')->search(
        {
            blog_is_hidden   => 0,
            blog_is_reply    => 1,
            blog_is_draft    => 0,
            blog_parent => $blog->blog_id,
        },
        {
            rows             => 5,
            page             => $page,
            order_by         => 'blog_date DESC',
        }
    );

    return [ $blog, 0, undef ] unless $replies;

    foreach my $reply (@$replies) {
        push @$ret, get_replies($c, $reply, $page);
    }
    [ $blog, scalar (@$replies), $ret ];
}

sub list : Local {
    # Retrieve the usual perl OO '$self' for this object. $c is the Catalyst
    # 'Context' that's used to 'glue together' the various components
    # that make up the application
    my ($self, $c, $page, $sort) = @_;
    # Retrieve all of the user records as book model objects and store in the
    # stash where they can be accessed by the TT template
    my $blog =  $c->model('YourSpaceDB::Blog')->search (
	{ 
		blog_is_hidden => '0', 
		blog_is_draft  => '0'
	},
	{ 
		        rows           => 50,
				page           => $page ? $page : 1,
			    order_by       => $sort ?$sort : 'blog_date DESC' 
		    }
	    );

	my $pager = $blog->pager;
   $c->stash->{next_page}      = $pager->next_page;
   $c->stash->{prev_page}      = $pager->previous_page;
   $c->stash->{first_page}     = $pager->first_page;
   $c->stash->{last_page}      = $pager->last_page;
   $c->stash->{current_page}   = $pager->current_page;
   $c->stash->{blogs} = [$blog->all];
   $c->stash->{template} = 'blog/list.tt2';
}

sub create : Local {
    my ($self, $c) = @_;
    if ( !( $c->user_exists ) ) {
        $c->res->redirect($c->uri_for('/', 
            {error_msg => "You don't have the correct privelages to post blogs"}));
        return;
    }
    # Set the TT template to use
    $c->stash->{template} = 'blog/create.tt2';
}

sub do_create : Local {
    my ($self, $c) = @_;
    ## local time
    my @lt = localtime(time);
    my $date = strftime('%Y-%m-%d %H:%M:%S', @lt);
    # Retrieve the values from the form
    my $author     = $c->req->param('author')     || 'Anonymous Lurker';
    my $title      = $c->req->param('title')      || 'N/A';
    my $tags       = $c->req->param('tags')       || 'N/A';
    my $text       = $c->req->param('text')       || 'N/A';
    my $is_hidden  = $c->req->param('is_hidden')  eq 'on' ? '1' : '0';
    my $is_draft   = $c->req->param('is_draft')   eq 'on' ? '1' : '0';
    
    if ($c->validate_captcha( $c->req->param( 'validate' ) ) ) {
        my $blog = $c->model('YourSpaceDB::Blog')->create({
            blog_author      => $author,
            blog_title       => $title,
            blog_tags        => $tags,
            blog_text        => $text,
            blog_is_hidden   => $is_hidden,
            blog_date        => $date,
            blog_parent      => 0,
            blog_is_draft    => $is_draft,
        });

        # Store new model object in stash
        $c->stash->{blog} = $blog;
    } else {
        
        $c->stash->{template} = 'blog/create.tt2';
        $c->stash->{error_msg} = "Invalid CAPTCHA, please try again";
        return;
        # Set the TT template to use
        
    }

    $c->stash->{template} = 'blog/create_done.tt2';
}

    
    
    


sub delete : Local {

    # $id = primary key of book to delete
    my ($self, $c, $id) = @_;
    
    # Search for the book and then delete it
    $c->model('YourSpaceDB::User')->search({user_id => $id})->delete_all;
    
    # Redirect the user back to the list page with status msg as an arg
    $c->res->redirect($c->uri_for('/blog/list', 
        {status_msg => "Blog deleted."}));

}

sub view : Local {
    # Retrieve the usual perl OO '$self' for this object. $c is the Catalyst
    # 'Context' that's used to 'glue together' the various components
    # that make up the application
    my ($self, $c, $blog_id) = @_;
    
    return $c->res->body("No blog id!") unless $blog_id =~ /\d/;

    # update blog's last access date (for recently active blogs)
    ## local time
    my @lt = localtime(time);   ## MOVE THIS LINE AND THE NEXT INTO A SEPARATE PM
    my $date = strftime('%Y-%m-%d %H:%M:%S', @lt);
    $c->model('YourSpaceDB::Blog')->update( { blog_last_accessed => $date }, { blog_id => $blog_id } );
    # Retrieve all of the user records as book model objects and store in the
    # stash where they can be accessed by the TT template
    $c->stash->{blog} = $c->model('YourSpaceDB::Blog')->find( { blog_id => $blog_id }); 
    $c->stash->{replies} =  [$c->model('YourSpaceDB::Blog')->search( { blog_parent => $blog_id })];   
    # Set the TT template to use.  You will almost always want to do this
    # in your action methods (action methods respond to user input in
    # your controllers).
    $c->stash->{template} = 'blog/view.tt2';

}

sub edit : Local {
    my ($self, $c, $username) = @_;
    $c->response->body("Nothing yet...");
}

sub search : Local {
    my ($self, $c) = @_;
    $c->stash->{template} = 'blog/search.tt2';

}

sub do_search : Local {
#my @terms   = split(' ', $query);
		my ($self, $c) = @_;
		
		my $query = $c->req->params->{'q'};
		$c->stash->{q} = $query;
		$c->stash->{results} = [
		$c->model('YourSpaceDB::Blog')->search(
			{ 
			-or => [
				blog_title  => 
					{ 
						'like', '%' .  $query . '%' 
					} ,
				blog_text  => 
					{ 
						'like', '%' .  $query . '%' 
					} ,
				blog_author  => 
					{ 
						'like', '%' .  $query . '%' 
					} ,
				blog_tags  => 
					{ 
						'like', '%' .  $query . '%' 
					} ,
				blog_date =>
					{ 
						'like', '%' .  $query . '%' 
					} ,
				]
			},
			{
				order_by => 'blog_date DESC',
			}
			)
		];
		
		$c->stash->{template} = 'blog/do_search.tt2';
}

sub do_rating : Local {

		my ($self, $c, $applaud_or_curse, $blog_id) = @_;
		
		if ( 
			$c->session->{vote_logged}      == 1 && 
			$c->session->{vote_post_number} == $blog_id
			) {
				$c->res->redirect(
				$c->uri_for('/blog/view/' . $blog_id, 
					{error_msg => "You've already voted on this post."}
				)
			);
		}
		my $rating = $c->model('YourSpaceDB::Blog')->find($blog_id);
		my $current_rating = $rating->blog_rating;
		if  ( $applaud_or_curse eq 'plus_plus' ) {
			$rating->blog_rating( $current_rating += 1 );
			$rating->update;
			$c->session->{vote_logged} = 1;
			$c->session->{vote_post_number} = $blog_id;
		} elsif ( $applaud_or_curse eq 'minus_minus' ) {
			$rating->blog_rating( $current_rating -= 1 );
			$rating->update;
			$c->session->{vote_logged} = 1;
			$c->session->{vote_post_number} = $blog_id;
		}
		$c->res->redirect(
			$c->uri_for('/blog/view/' . $blog_id, 
				{
				status_msg => "Vote registered!",
				}
			)
		);

}

sub reply : Local {
   my ($self, $c, $blog_id) = @_;
    
    # Set the TT template to use
    $c->stash->{blog}        = $c->model('YourSpaceDB::Blog')->find($blog_id);
    $c->stash->{replies}     = [
        $c->model('YourSpaceDB::Blog')->search( 
        { 
         blog_is_reply    => 1, 
         blog_parent => $blog_id,
         blog_is_draft    => 0,
        }
        )
    ];
    $c->stash->{recurse} = 1;
    $c->stash->{template} = 'blog/reply.tt2';
}


sub do_reply : Local {
    my ($self, $c) = @_;
    
    ## local time
    my @lt = localtime(time);
    my $date = strftime('%Y-%m-%d %H:%M:%S', @lt);
    # Retrieve the values from the form
    my $author     = $c->request->params->{author}     || 'Anonymous Lurker';
    my $title      = $c->request->params->{title}      || 'N/A';
    my $tags       = $c->request->params->{tags}       || 'N/A';
    my $text       = $c->request->params->{text}       || 'N/A';
    my $is_hidden  = $c->request->params->{is_hidden} eq 'on' ? '1': '0';
    my $parent_blog= $c->request->params->{parent_blog};
    my $is_draft   = $c->request->params->{is_draft}   eq 'on' ? '1' : '0';

    if ($c->validate_captcha( $c->req->param( 'validate' ) ) ) {

        my $blog = $c->model('YourSpaceDB::Blog')->create({
            blog_author     => $author,
            blog_title      => $title,
            blog_tags       => $tags,
            blog_text       => $text,
            blog_is_hidden  => $is_hidden,
            blog_date       => $date,
            blog_parent     => $parent_blog,
            blog_is_reply   => 1,
            blog_is_draft    => $is_draft,
        });

        # Store new model object in stash
        $c->stash->{blog} = $blog;

    } else {
        
        $c->stash->{template} = 'blog/reply.tt2';
        $c->stash->{error_msg} = "Invalid CAPTCHA, please try again";
        $c->forward( "/blog/reply/", [ $parent_blog ] );
        return;
        
    }
   
    $c->stash->{template} = 'blog/do_reply.tt2';
}

=head1 AUTHOR

A clever guy

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;
